<template>
  <div class="select-tab">
    <span @click="clickItem(item)" :class="{ isSelect: item.isSelect }" class="item" v-for="item in showList" :key="item.value">
      {{ item.label }}
    </span>
  </div>
</template>

<script setup lang="ts">
import { Ref, ref, watch } from "vue";

type SelectObj = {
  value: number;
  label: string;
  isSelect?: boolean;
};

let showList = ref([]) as Ref<SelectObj[]>;

interface selectTabProps {
  modelValue: number | number[];
  selectList: SelectObj[];
  isMutiply?: boolean;
}
const { isMutiply, modelValue, selectList } = withDefaults(defineProps<selectTabProps>(), {
  isMutiply: false
});

interface selectTabEmits {
  (e: "update:modelValue", item: number | number[]): void;
}
const $emit = defineEmits<selectTabEmits>();

/**
 * 改变展示的数组
 */
const changeSelectList = (value: number | number[]) => {
  if (isMutiply) {
    showList.value = selectList.map(row => {
      return {
        value: row.value,
        label: row.label,
        isSelect: (value as number[]).indexOf(row.value) > -1
      };
    });
    return;
  }
  showList.value = selectList.map(row => {
    return {
      value: row.value,
      label: row.label,
      isSelect: row.value == value
    };
  });
};

/**
 * 点击某个项
 */
const clickItem = (row: SelectObj) => {
  if (isMutiply) {
    let chooseList = showList.value
      .map((item: SelectObj) => {
        return {
          ...item,
          isSelect: row.value == item.value ? !item.isSelect : item.isSelect
        };
      })
      .filter((k: SelectObj) => k.isSelect)
      .map((j: SelectObj) => {
        return j.value;
      });
    changeSelectList(chooseList);
    $emit("update:modelValue", chooseList);
  } else {
    changeSelectList(row.value);
    $emit("update:modelValue", row.value);
  }
};

watch(
  () => modelValue,
  newVal => {
    changeSelectList(newVal);
  },
  { immediate: true, deep: true }
);
</script>

<style scoped lang="scss">
.select-tab {
  .item {
    display: inline-block;
    width: 100px;
    height: 30px;
    border: 1px solid #ccc;
    line-height: 30px;
    text-align: center;
    cursor: pointer;
  }
  .isSelect {
    background: red;
    color: #fff;
  }
}
</style>
